package com.smec.moblie.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.google.gson.Gson;
import com.smec.moblie.R;
import com.smec.moblie.bean.LoginBackBean;
import com.smec.moblie.bean.LoginPostBean;
import com.smec.moblie.control.LogControl;
import com.smec.moblie.control.MainControl;
import com.smec.moblie.crash.CustomCrashHandler;
import com.smec.moblie.crash.ExitAppUtils;
import com.smec.moblie.flyn.Eyes;
import com.smec.moblie.service.MntJobService;
import com.smec.moblie.util.Util;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;

/**
 * 登入界面activity
 *
 * @author sunyubo
 */
public class LoginActivity extends BaseActivity {
    /************************** 控件 **************************/
    /****
     * 用户名Edit
     ****/
    private EditText editText_userName;
    /****
     * 密码Edit
     ****/
    private EditText editText_password;
    /****
     * 错误信息显示text
     ****/
    private TextView textView_errMsg;
    /****
     * 版本信息text
     ****/
    private TextView textView_version;
    /****
     * 登入按钮button
     ****/
    private Button button_login;
    /****
     * 记住密码CheckBox
     ****/
    private CheckBox checkbox_rememberPassword;

    /************************** 变量 **************************/
    /****
     * 用户名变量
     ****/
    private String USERNAME = "";
    /****
     * 密码变量
     ****/
    private String PASSWD = "";
    /****
     * 是否保存密码
     ****/
    private Boolean isSavePassword;

    /************************** 其他 **************************/
    /****
     * 提示
     ****/
    private SVProgressHUD pd = null;
    /****
     * 存储账号密码SharedPreferences
     ****/
    private SharedPreferences mySharedPreferences;

    @Override
    protected void setContentView() {
        setContentView(R.layout.remes_act_login);
    }

    /**
     * 初始化view
     */
    private void initView2() {
        editText_userName = (EditText) findViewById(R.id.editText_userName);
        editText_password = (EditText) findViewById(R.id.editText_password);
        textView_errMsg = (TextView) findViewById(R.id.textView_errMsg);
        textView_version = (TextView) findViewById(R.id.textView_version);
        button_login = (Button) findViewById(R.id.button_login);
        checkbox_rememberPassword = (CheckBox) findViewById(R.id.checkbox_rememberPassword);
    }


    /**
     * 初始化view
     */
    @Override
    protected void initView() {
        Eyes.translucentStatusBar(LoginActivity.this, true);

        CustomCrashHandler customCrashHandler = CustomCrashHandler.getInstance();
        customCrashHandler.setCustomCrashHanler(getApplicationContext());
        ExitAppUtils.getInstance().addActivity(this);
        isShowVersionDialog = false;
        // 获取SharedPreferences中保存的账号密码，没有返回""
        mySharedPreferences = getSharedPreferences(
                "ElevatorSharedPreferences", LoginActivity.MODE_PRIVATE);
        USERNAME = mySharedPreferences.getString("USERNAME", "");
//        PASSWD = mySharedPreferences.getString("PASSWD", "");
        isSavePassword = mySharedPreferences.getBoolean("IS_SAVE_PASSWORD", false);
        boolean isSetPassWord = mySharedPreferences.getBoolean("isSetPassWord", false);
        // 开始定位服务
//        PollingUtils.startPollingService(this, 60, SmecMntMapService.class, SmecMntMapService.ACTION, "SmecMntMapService");
        if (isSetPassWord) {

            Intent intent = new Intent(LoginActivity.this,
                    ConfirmPatternActivity.class);
            startActivity(intent);
            finish();
        }
        MntJobService.startMntJobService(this);//导入本地工作项

        initView2();// 初始化view

        initListener();// 初始化Listener

        initData();// 初始化数据
    }

    @Override
    protected void getData() {

    }

    /**
     * 初始化Listener
     */
    private void initListener() {
        button_login.setOnClickListener(new MyOnClickListener());
        checkbox_rememberPassword.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
    }

    /**
     * 初始化数据
     */
    private void initData() {
        textView_version.setText("v " + getAppVersionName(getApplicationContext()) + " 正式版");// 设置版本号
        editText_userName.setText(USERNAME);
        if (isSavePassword) {
            editText_password.setText(PASSWD);
        } else {
            editText_password.setText("");
        }
        checkbox_rememberPassword.setChecked(isSavePassword);
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 按钮点击事件
     *
     * @author sunyubo
     */
    private class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button_login:
                    USERNAME = editText_userName.getText().toString();
                    PASSWD = editText_password.getText().toString();
                    USERNAME = Util.exChangeAtoa(USERNAME);
                    if ("".equals(USERNAME) || "".equals(PASSWD)) {
                        button_login.startAnimation(AnimationUtils.loadAnimation(
                                LoginActivity.this, R.anim.shake));
                        textView_errMsg.setText("用户名和密码不能为空");
                        textView_errMsg.setVisibility(View.VISIBLE);
                    } else {
                        // 显示等待进度条
                        if (pd == null) {
                            pd = new SVProgressHUD(LoginActivity.this);
                            pd.showWithStatus("正在登入...");
                        } else {
                            if (!pd.isShowing()) {
                                pd.showWithStatus("正在登入...");
                            }
                        }
                        button_login.setEnabled(false);

//                        new GetLoginCheckAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        loginCheck();
                    }
                    break;

                default:
                    break;
            }

        }

    }

    /**
     * 是否保存密码监听
     **/
    private class MyOnCheckedChangeListener implements CheckBox.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // 实例化SharedPreferences.Editor对象
            SharedPreferences.Editor editor = mySharedPreferences.edit();
            editor.putBoolean("IS_SAVE_PASSWORD", isChecked);
            // 提交当前数据
            editor.commit();
        }
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }


    /***
     * 登入检验
     */
    private void loginCheck() {
        LoginPostBean loginPostBean = new LoginPostBean();
        loginPostBean.setUsername(USERNAME);
        loginPostBean.setPassword(PASSWD);
//        loginPostBean.setAppVersion(PublicControl.getAppVersionName(context));
//        loginPostBean.setDevice(PublicControl.getDeviceId(context));
        final Gson gson = new Gson();
        String jsonData = gson.toJson(loginPostBean);
        LogControl.log("~~~ login jsonData = " + jsonData);
        OkHttpUtils.postString().addHeader(TRACE, MainControl.getVersionCheck(LoginActivity.this, "SmecAuthorizationService")).
                url(LOGIN_URL).content(jsonData).mediaType(MediaType.parse("application/json; charset=utf-8")).
                build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                textView_errMsg.setVisibility(View.VISIBLE);
                textView_errMsg.setText("网络连接错误，请检查网络");
                LogControl.log("~~~ login Error = " + e.getMessage());
                if (pd.isShowing()) {
                    pd.dismiss();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                LogControl.log("~~~ login response = " + response);
                button_login.setEnabled(true);
                try {
                    LoginBackBean loginBackBean = gson.fromJson(response.toString(), LoginBackBean.class);

                    if (loginBackBean.getCode().equals(SUCCESS)) {
                        boolean isSetPassWord = mySharedPreferences.getBoolean("isSetPassWord", false);
                        Intent intent = new Intent(LoginActivity.this,
                                SetPatternActivity.class);

                        intent.putExtra("USERNAME", USERNAME);
                        intent.putExtra("PASSWD", PASSWD);
                        intent.putExtra("TRUENAME", loginBackBean.getData().getUserName());
                        startActivity(intent);

                        // 实例化SharedPreferences.Editor对象
                        SharedPreferences.Editor editor = mySharedPreferences
                                .edit();
                        // 用putString的方法保存数据
                        editor.putString("USERNAME", USERNAME);
                        editor.putString("PASSWD", PASSWD);
                        editor.putString("TRUENAME", loginBackBean.getData().getUserName());
                        editor.putString("TOKEN", loginBackBean.getData().getToken());
                        editor.putString("userId",loginBackBean.getData().getUserId());
                        editor.putString("role",loginBackBean.getData().getUserRole());
                        editor.putString("isStation",loginBackBean.getData().getIsStationOnline());
                        // 提交当前数据
                        editor.commit();
                        JPushInterface.init(getApplicationContext());
                        // 调用JPush API设置Alias
                        try {
                            JPushInterface.setAliasAndTags(getApplicationContext(),
                                    USERNAME, null);
                            Log.i("", "jpush注册:" + USERNAME);
                        } catch (Exception e) {
                            Log.e("", "JPUSH register err:" + e.toString());
                            // Log.e(TAG, "JPUSH register err:" +
                            // e.getMessage());
                        }
                        LoginActivity.this.finish();
                    } else {
                        textView_errMsg.setVisibility(View.VISIBLE);
                        textView_errMsg.setText(loginBackBean.getUserMsg());
                    }
                } catch (Exception e) {
                    textView_errMsg.setVisibility(View.VISIBLE);
                    textView_errMsg.setText("连接服务器错误");
                }
                if (pd.isShowing()) {
                    pd.dismiss();
                }
            }

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
            }

            @Override
            public void onAfter(int id) {
                super.onAfter(id);
            }


        });
    }

    /**
     * 检验用户名密码AsyncTask
     *
     * @author sunyubo
     */
    private class GetLoginCheckAsyncTask extends AsyncTask<Void, Void, Void> {
        String ret = null;

        @Override
        protected Void doInBackground(Void... params) {

            try {
                ret = MainControl.checkLogon(USERNAME, PASSWD);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            }
            Log.i("", "~~~Login ret=" + ret);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            button_login.setEnabled(true);

            if (null != ret) {
                if (!"用户名或密码错误".equals(ret) && !"解析错误".equals(ret)) {
                    boolean isSetPassWord = mySharedPreferences.getBoolean("isSetPassWord", false);
                    Intent intent = new Intent(LoginActivity.this,
                            SetPatternActivity.class);

                    intent.putExtra("USERNAME", USERNAME);
                    intent.putExtra("PASSWD", PASSWD);
                    intent.putExtra("TRUENAME", ret);
                    startActivity(intent);

                    // 实例化SharedPreferences.Editor对象
                    SharedPreferences.Editor editor = mySharedPreferences
                            .edit();
                    // 用putString的方法保存数据
                    editor.putString("USERNAME", USERNAME);
                    editor.putString("PASSWD", PASSWD);
                    editor.putString("TRUENAME", ret);
                    editor.putString("TOKEN", "");
                    // 提交当前数据
                    editor.commit();
                    JPushInterface.init(getApplicationContext());
                    // 调用JPush API设置Alias
                    try {
                        JPushInterface.setAliasAndTags(getApplicationContext(),
                                USERNAME, null);
                        Log.i("", "jpush注册:" + USERNAME);
                    } catch (Exception e) {
                        Log.e("", "JPUSH register err:" + e.toString());
                        // Log.e(TAG, "JPUSH register err:" +
                        // e.getMessage());
                    }
                    LoginActivity.this.finish();
                } else if ("解析错误".equals(ret)) {
                    textView_errMsg.setVisibility(View.VISIBLE);
                    textView_errMsg.setText("连接服务器错误");
                } else {
                    textView_errMsg.setVisibility(View.VISIBLE);
                    textView_errMsg.setText("帐号密码错误");
                }
            } else {
                textView_errMsg.setVisibility(View.VISIBLE);
                textView_errMsg.setText("网络连接错误，请检查网络");
            }
            if (pd.isShowing()) {
                pd.dismiss();
            }
            super.onPostExecute(result);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

